package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.device.DeviceDetailVo;
import com.zzyl.nursing.vo.device.ProductVo;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 设备模块Service业务层处理
 *
 * @author fan
 * @date 2025-06-08
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询设备模块
     *
     * @param id 设备模块主键
     * @return 设备模块
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备模块列表
     *
     * @param device 设备模块
     * @return 设备模块
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备模块
     *
     * @param device 设备模块
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备模块
     *
     * @param device 设备模块
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备模块
     *
     * @param ids 需要删除的设备模块主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备模块信息
     *
     * @param id 设备模块主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //1,去iot平台获取产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        List<ProductSummary> products = response.getProducts();
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("获取产品列表失败");
        }

        //2，将数据存入redis
        redisCache.setCacheObject("iot:all-product", JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        String cacheObject = redisCache.getCacheObject("iot:all-product");
        List<ProductVo> list = JSONUtil.toList(cacheObject, ProductVo.class);
        return list;
    }

    /**
     * 注册设备
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1,查询设备名称是否重复
        long count1 = this.count(new LambdaQueryWrapper<Device>()
                .eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count1 > 0) {
            throw new BaseException("设备名称重复");
        }

        //2，查询设备标识符是否重复
        long count2 = this.count(new LambdaQueryWrapper<Device>()
                .eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count2 > 0) {
            throw new BaseException("设备标识符重复");
        }

        //3，查询同一位置是否添加同类设备
        long count3 = this.count(new LambdaQueryWrapper<Device>()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()));
        if (count3 > 0) {
            throw new BaseException("同一位置不能添加同类设备");
        }

        //4，iot 注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        body.withProductId(deviceDto.getProductKey());
        //配置密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfobody = new AuthInfo();
        authInfobody.withAuthType("SECRET")
                .withSecret(secret)
                .withSecureAccess(true);
        body.withAuthInfo(authInfobody);

        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("添加设备失败");
        }

        //5，插入数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        this.save(device);

    }

    /**
     * 获取设备详细信息
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查华为云
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询IOT平台设备信息失败");
        }
        String status = response.getStatus();
        String activeTime = response.getActiveTime();

        //查询device表
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(queryWrapper);
        //查询创建人信息sys_user表
        Long createBy = Long.valueOf(device.getCreateBy());
        String creator = sysUserMapper.selectUserById(createBy).getUserName();

        //封装信息返回
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setCreator(creator);
        deviceDetailVo.setDeviceStatus(status);
        if (StringUtils.isNotEmpty(activeTime)) {
            // 1. 解析为 Instant（自动识别 Z 表示 UTC 时间）
            Instant instant = Instant.parse(activeTime);
            // 2. 转换为 LocalDateTime（默认系统时区）
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            deviceDetailVo.setActiveTime(localDateTime);
        }

        return deviceDetailVo;

    }

    /**
     * 修改设备
     */
    @Override
    public int edit(DeviceDto deviceDto) {
        //构建请求信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("修改设备信息失败");
        }

        //修改数据库信息
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        return deviceMapper.updateById(device);
    }

    /**
     * 删除设备
     */
    @Override
    public int deleteDevice(String iotId) {
        //删除ito设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("删除设备失败");
        }

        //删除数据库对应设备
        return this.remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId)) ? 1 : 0;
    }

    /**
     * 查询设备上报数据
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //创建查询设备影子的请求
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备数据失败");
        }

        //封装返回的数据
        DeviceShadowData shadowData = response.getShadow().get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        // 获取时间
        String eventTime = reported.getEventTime();
        // 自定义格式器支持 "20250609T011144Z"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
        Instant instant = Instant.from(formatter.parse(eventTime));
        // 转换为 LocalDateTime（默认系统时区）
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        //处理kv
        Map<String, Object> properties = (Map<String, Object>) reported.getProperties();
        List<Map<String, Object>> list = new ArrayList<>();
        properties.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", localDateTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 查询产品详情(报警规则模块使用)
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询产品信息失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();

//        //封装返回数据
//        Map<String, Object> map = new HashMap<>();
//        map.put("service_id", serviceCapability.getServiceId());
//        map.put("service_type", serviceCapability.getServiceType());
//        map.put("properties",  serviceCapability.getProperties());
//        map.put("option", serviceCapability.getOption());

        return serviceCapabilities;
    }

}
